<?php

namespace App\Http\Controllers;

use App\Events\ClickLogEvent;
use App\Events\OrderCompletedEvent;
use App\Extend\IPweb;
use App\Models\ClickLog;
use App\Models\Config;
use App\Models\OrderInfo;
use App\Models\StaticRegion;
use App\Services\OrderService;
use App\Services\PaymentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class BuyController extends Controller
{
    /**
     * 套餐列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function goods(Request $request)
    {
        $type = $request->input('type', 'dynamic');
        $lang = $request->input('lang', 'en');
        $goods = config('goods');
        $data = $goods[$type][$lang];
        array_multisort(array_column($data, 'amount'), SORT_ASC, $data);

        return response()->json([
            'errcode' => 0,
            'errmsg' => '',
            'data' => $data
        ]);
    }

    /**
     * 订单
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function dynamic(Request $request)
    {
        try {
            $goods_id = $request->input('goods_id');
            $pay_way = $request->input('pay_way');

            if (empty($goods_id)) {
                $errmsg = App::getLocale() == 'en' ? 'Please select a package.' : '请选择套餐';
                throw new \Exception($errmsg, -1);
            }

            if (empty($pay_way)) {
                $errmsg = App::getLocale() == 'en' ? 'Please select a payment method' : '请选择付款方式';
                throw new \Exception($errmsg);
            }

            $user_id = auth()->id();
            $goods_config = config('goods.dynamic');
            $goods_list = $goods_config[App::getLocale()];
            if (!in_array($goods_id, array_keys($goods_list))) {
                $errmsg = App::getLocale() == 'en' ? 'The package does not exist.' : '套餐不存在';
                throw new \Exception($errmsg);
            }

            $goods_info = $goods_list[$goods_id];
            $title = $goods_info['title'];
            $combo = $goods_info['combo'];
            $amount = $goods_info['amount'];
            $quantity = $goods_info['quantity'];
            $desc = $title . $combo;

            if ($pay_way == "usdt") {
                $count = OrderInfo::where('goods_id', $goods_id)->where('pay_way', 'usdt')->count();
                $count = $count > 0 ? $count + 1 : 1;
                if ($count > 999) {
                    $errmsg = App::getLocale() == 'en' ? 'Please change to another payment method' : '请更换其他支付方式';
                    throw new \Exception($errmsg);
                }
                $amount = (int)$amount . '.' . str_pad($count, 3, 0, STR_PAD_LEFT);
            }

            $order_nu = 'IPX' . date('YmdHis') . rand(100000, 999999);

            // 记录点击事件
            $ip = $request->header('X-Real-IP') ?? $request->ip();
            $userAgent = $request->header('User-Agent');
            $isMobileDevice = preg_match('/(android|iphone|ipod|blackberry|windows phone)/i', $userAgent);
            $clickLog = ClickLog::create([
                'user_id' => $user_id,
                'event_type' => 'order',
                'ip' => $ip,
                'event_data' => json_encode([
                    'goods_id' => $goods_id,
                    'pay_way' => $pay_way,
                ]),
                'goods_id' => $goods_id,
                'pay_way' => $pay_way,
                'is_mobile' => (bool)$isMobileDevice,
                'user_agent' => $userAgent,
                'create_day' => date('Y-m-d'),
                'order_nu' => $order_nu,
                'amount' => $amount
            ]);
            event(new ClickLogEvent($clickLog));

            // TODO 测试账号
            if ($user_id == 100060 || $user_id == 101565 || $user_id == 102066) {
                $amount = 0.01;
            }

            if ($goods_id == 5) {
                $trial_order = OrderInfo::where('user_id', $user_id)->where('goods_id', 5)->where('status', 1)->exists();
                if ($trial_order) {
                    $errmsg = App::getLocale() == 'en' ? 'The trial version is available for purchase only once.' : '体验版只允许购买一次';
                    throw new \Exception($errmsg);
                }
            }

            $order_data = [
                'user_id' => $user_id,
                'order_nu' => $order_nu,
                'goods_id' => $goods_id,
                'goods_info' => $desc,
                'proxy_type' => 1,
                'amount' => $amount,
                'quantity' => $quantity,
                'pay_way' => $pay_way,
                'create_day' => date('Y-m-d')
            ];
            $return_url = env('APP_URL') . '/manage/center/rechargeDetails?name=1';
            $result = (new PaymentService())->createPayment(Auth::user(), $pay_way, $order_nu, $amount, $desc, $return_url);
            if (empty($result)) {
                $errmsg = App::getLocale() == 'en' ? 'Order failure' : '下单失败';
                throw new \Exception($errmsg);
            }

            $order_data['amount'] = $result['amount'];
            $order_data['transaction_id'] = $result['transaction_id'];
            $order_data['transaction_platform'] = $result['transaction_platform'];

            $data = OrderInfo::create($order_data);
            if (empty($data)) {
                $errmsg = App::getLocale() == 'en' ? 'Order failure' : '下单失败';
                throw new \Exception($errmsg);
            }

            $data->locale = App::getLocale();
            $data->redirect_url = $result['redirect_url'] ?? '';
            $data->client_secret = $result['client_secret'] ?? '';
            if (empty($data->redirect_url)) {
                $config = Config::first();
                if ($pay_way == 'usdt') {
                    $data->qrcode = $config->usdt_qrcode;
                    $data->usdt_address = $config->usdt_address;
                    $data->pay_tip = __('buy.pay.usdt_tip');
                    $data->payment_note = __('buy.pay.payment_note');
                }
            }

            return response()->json([
                'errcode' => 0,
                'errmsg' => __('common.success'),
                'data' => $data
            ]);
        } catch (\Exception $e) {
            Log::error("创建订单失败：" . $e->getMessage() . ' ' . $e->getLine() . ' ' . $e->getFile());
            return response()->json([
                'errcode' => -1,
                'errmsg' => $e->getMessage(),
            ]);
        }
    }

    /**
     * 订单
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function static(Request $request)
    {
        if (App::getLocale() == 'en') {
            $static_region = Cache::remember('static_region_en', 86400, function () {
                return StaticRegion::pluck('name', 'code')->toArray();
            });
        } else {
            $static_region = Cache::remember('static_region_zh', 86400, function () {
                return StaticRegion::pluck('alias', 'code')->toArray();
            });
        }
        if (App::getLocale() == 'en') {
            $line_types = [
                '1' => 'basics',
                '2' => 'standard',
                '3' => 'advanced'
            ];
        } else {
            $line_types = [
                '1' => '基础',
                '2' => '标准',
                '3' => '高端'
            ];
        }

        try {
            $country_code = $request->input('country_code');
            $line_type = $request->input('line_type');
            $business = $request->input('business');
            $days = $request->input('days');
            $quantity = $request->input('quantity');
            $pay_way = $request->input('pay_way');

            if (empty($country_code)) {
                $errmsg = App::getLocale() == 'en' ? 'Please select a region.' : '请选择地区';
                throw new \Exception($errmsg, -1);
            }
            if (!in_array($country_code, array_keys($static_region))) {
                $errmsg = App::getLocale() == 'en' ? 'The region you selected is invalid.' : '您选择的地区无效';
                throw new \Exception($errmsg, -1);
            }

            if (empty($line_type)) {
                $errmsg = App::getLocale() == 'en' ? 'Please select the IP type.' : '请选择IP类型';
                throw new \Exception($errmsg, -1);
            }
            if (!in_array($line_type, array_keys($line_types))) {
                $errmsg = App::getLocale() == 'en' ? 'The IP type you selected is invalid.' : '您选择的IP类型无效';
                throw new \Exception($errmsg, -1);
            }

            if (empty($business)) {
                $errmsg = App::getLocale() == 'en' ? 'Please select the business purpose.' : '请选择业务用途';
                throw new \Exception($errmsg, -1);
            }

            if (empty($days)) {
                $errmsg = App::getLocale() == 'en' ? 'Please select a package.' : '请选择套餐';
                throw new \Exception($errmsg, -1);
            }
            if (!in_array($days, [1, 7, 15, 30, 60, 90, 365])) {
                $errmsg = App::getLocale() == 'en' ? 'The package you selected is invalid.' : '您选择的套餐无效';
                throw new \Exception($errmsg, -1);
            }

            if (empty($quantity)) {
                $errmsg = App::getLocale() == 'en' ? 'Please enter the quantity you wish to purchase.' : '请输入购买数量';
                throw new \Exception($errmsg, -1);
            }
            if ($quantity > 500) {
                $errmsg = App::getLocale() == 'en' ? 'Exceeding the purchase limit' : '购买数量超出限制';
                throw new \Exception($errmsg, -1);
            }

            if (empty($pay_way)) {
                $errmsg = App::getLocale() == 'en' ? 'Please select a payment method' : '请选择付款方式';
                throw new \Exception($errmsg, -1);
            }

            $stock = (new IPweb())->stock($country_code, $business, $line_type);
            Log::info('静态IP库存信息：地区 ' . $country_code . ' 业务 ' . $business . ' IP类型 ' . $line_type . ' 库存 ' . $stock);
            if ($stock < ($quantity * 2)) {
                $errmsg = App::getLocale() == 'en' ? 'Inventory is insufficient. Please try again later or contact the customer service staff.' : '库存不足，请稍后再试，或者联系客服人员';
                throw new \Exception($errmsg, -1);
            }

            $user_id = auth()->id();
            $goods_id = 2001;
            $order_nu = 'IPX' . date('YmdHis') . rand(100000, 999999);
            $desc = $static_region[$country_code] . '-' . $line_types[$line_type] . '-' . $business . '-' . $days . '%s-' . $quantity . 'IP';
            $desc = App::getLocale() == 'en' ? sprintf($desc, 'day') : sprintf($desc, '天');

            $goods_config = config('goods');
            $goods_pirces = $line_type == 2 ? $goods_config['static']['standard'] : $goods_config['static']['professional'];
            $amount = bcmul($goods_pirces[$days], $quantity, 2);
            if ($pay_way == 'usdt') {
                $count = OrderInfo::where('goods_id', $goods_id)->where('quantity', $quantity)->where('pay_way', 'usdt')->count();
                $count = $count > 0 ? $count + 1 : 1;
                if ($count > 999) {
                    $errmsg = App::getLocale() == 'en' ? 'Please change to another payment method' : '请更换其他支付方式';
                    throw new \Exception($errmsg);
                }
                $count = str_pad($count, 3, '0', STR_PAD_LEFT);

                $amount = floatval($amount);
                // 分割整数和小数部分
                $parts = explode('.', $amount);
                $primary = intval($parts[0]);
                $decimal = isset($parts[1]) ? str_pad($parts[1], 3, '0') : '000';

                // 将小数部分补全为3位（右侧补零）
                $decimal = str_pad($decimal, 3, '0');

                // 将小数部分和count转为整数相加，再补全为3位
                $newDecimal = (int)$decimal + (int)$count;
                $newDecimal = str_pad($newDecimal, 3, '0', STR_PAD_LEFT);

                // 处理可能的进位（如果小数部分相加超过999）
                if ($newDecimal > 999) {
                    $primary = $primary + 1;
                    $newDecimal = $newDecimal - 1000;
                    $newDecimal = str_pad($newDecimal, 3, '0', STR_PAD_LEFT);
                }

                $amount = $primary . '.' . $newDecimal;
            }

            // 记录点击事件
            $client_ip = $request->header('X-Real-IP') ?? $request->ip();
            $userAgent = $request->header('User-Agent');
            $isMobileDevice = preg_match('/(android|iphone|ipod|blackberry|windows phone)/i', $userAgent);
            $clickLog = ClickLog::create([
                'user_id' => $user_id,
                'event_type' => 'order',
                'ip' => $client_ip,
                'event_data' => json_encode([
                    'goods_id' => $goods_id,
                    'pay_way' => $pay_way,
                ]),
                'pay_way' => $pay_way,
                'is_mobile' => (bool)$isMobileDevice,
                'user_agent' => $userAgent,
                'create_day' => date('Y-m-d'),
                'order_nu' => $order_nu,
                'amount' => $amount
            ]);
            event(new ClickLogEvent($clickLog));

            if (in_array($user_id, [102066])) {
                $amount = 0.01;
            }

            $order_data = [
                'user_id' => $user_id,
                'order_nu' => $order_nu,
                'goods_id' => $goods_id,
                'goods_info' => $desc,
                'proxy_type' => 2,
                'amount' => $amount,
                'quantity' => $quantity,
                'pay_way' => $pay_way,
                'extend' => json_encode([
                    'country_code' => $country_code,
                    'line_type' => $line_type,
                    'business' => $business,
                    'days' => $days,
                    'quantity' => $quantity
                ]),
                'create_day' => date('Y-m-d')
            ];
            $return_url = env('APP_URL') . '/manage/center/rechargeDetails?name=2';
            $result = (new PaymentService())->createPayment(Auth::user(), $pay_way, $order_nu, $amount, $desc, $return_url);
            if (empty($result)) {
                $errmsg = App::getLocale() == 'en' ? 'Order failure' : '下单失败';
                throw new \Exception($errmsg);
            }

            $order_data['amount'] = $result['amount'];
            $order_data['transaction_id'] = $result['transaction_id'];
            $order_data['transaction_platform'] = $result['transaction_platform'];

            $data = OrderInfo::create($order_data);
            if (empty($data)) {
                $errmsg = App::getLocale() == 'en' ? 'Order failure' : '下单失败';
                throw new \Exception($errmsg);
            }

            $data->locale = App::getLocale();
            $data->redirect_url = $result['redirect_url'] ?? '';
            $data->client_secret = $result['client_secret'] ?? '';
            if (empty($data->redirect_url)) {
                $config = Config::first();
                if ($pay_way == 'usdt') {
                    $data->qrcode = $config->usdt_qrcode;
                    $data->usdt_address = $config->usdt_address;
                    $data->pay_tip = __('buy.pay.usdt_tip');
                    $data->payment_note = __('buy.pay.payment_note');
                }
            }

            return response()->json([
                'errcode' => 0,
                'errmsg' => __('common.success'),
                'data' => $data
            ]);
        } catch (\Exception $e) {
            Log::error("创建订单失败：" . $e->getMessage() . ' ' . $e->getLine() . ' ' . $e->getFile());
            return response()->json([
                'errcode' => -1,
                'errmsg' => $e->getMessage(),
            ]);
        }
    }

    /**
     * 静态订单续费
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function staticRenew(Request $request)
    {
        if (App::getLocale() == 'en') {
            $static_region = Cache::remember('static_region_en', 86400, function () {
                return StaticRegion::pluck('name', 'code')->toArray();
            });
        } else {
            $static_region = Cache::remember('static_region_zh', 86400, function () {
                return StaticRegion::pluck('alias', 'code')->toArray();
            });
        }
        if (App::getLocale() == 'en') {
            $line_types = [
                '1' => 'basics',
                '2' => 'standard',
                '3' => 'advanced'
            ];
        } else {
            $line_types = [
                '1' => '基础',
                '2' => '标准',
                '3' => '高端'
            ];
        }

        try {
            $order_nu = $request->input('order_nu');
            $renew_ip = $request->input('ip');
            $renew_days = $request->input('days');
            $pay_way = $request->input('pay_way');

            if (empty($order_nu)) {
                $errmsg = App::getLocale() == 'en' ? 'Please provide the source order number.' : '请提供源订单号';
                throw new \Exception($errmsg, -1);
            }

            if (empty($renew_ip)) {
                $errmsg = App::getLocale() == 'en' ? 'Please provide the IP that needs to be renewed.' : '请提供要续费的IP';
                throw new \Exception($errmsg, -1);
            }

            if (empty($renew_days)) {
                $errmsg = App::getLocale() == 'en' ? 'Please select a package.' : '请选择套餐';
                throw new \Exception($errmsg, -1);
            }
            if (!in_array($renew_days, [1, 7, 15, 30, 60, 90, 365])) {
                $errmsg = App::getLocale() == 'en' ? 'The package you selected is invalid.' : '您选择的套餐无效';
                throw new \Exception($errmsg, -1);
            }

            if (empty($pay_way)) {
                $errmsg = App::getLocale() == 'en' ? 'Please select a payment method' : '请选择付款方式';
                throw new \Exception($errmsg, -1);
            }

            $source_order_info = OrderInfo::where('order_nu', $order_nu)->first();
            $extend = json_decode($source_order_info->extend, true);
            $country_code = $extend['country_code'];
            $line_type = $extend['line_type'];
            $business = $extend['business'];
            $quantity = 1;

            $stock = (new IPweb())->stock($country_code, $business, $line_type);
            Log::info('静态IP库存信息：地区 ' . $country_code . ' 业务 ' . $business . ' IP类型 ' . $line_type . ' 库存 ' . $stock);
            if ($stock < ($quantity * 2)) {
                $errmsg = App::getLocale() == 'en' ? 'Inventory is insufficient. Please try again later or contact the customer service staff.' : '库存不足，请稍后再试，或者联系客服人员';
                throw new \Exception($errmsg, -1);
            }

            $user_id = auth()->id();
            $goods_id = 2001;
            $order_nu = 'IPX' . date('YmdHis') . rand(100000, 999999);
            $desc = $static_region[$country_code] . '-' . $line_types[$line_type] . '-' . $business . '-' . $renew_days . '%s-' . $quantity . 'IP';
            $desc = App::getLocale() == 'en' ? sprintf($desc, 'day') : sprintf($desc, '天');

            $goods_config = config('goods');
            $goods_pirces = $line_type == 2 ? $goods_config['static']['standard'] : $goods_config['static']['professional'];
            $amount = $goods_pirces[$renew_days] * $quantity;
            if ($pay_way == 'usdt') {
                $count = OrderInfo::where('goods_id', $goods_id)->where('quantity', $quantity)->where('pay_way', 'usdt')->count();
                $count = $count > 0 ? $count + 1 : 1;
                if ($count > 999) {
                    $errmsg = App::getLocale() == 'en' ? 'Please change to another payment method' : '请更换其他支付方式';
                    throw new \Exception($errmsg);
                }
                $count = str_pad($count, 3, '0', STR_PAD_LEFT);

                $amount = floatval($amount);
                // 分割整数和小数部分
                $parts = explode('.', $amount);
                $primary = intval($parts[0]);
                $decimal = isset($parts[1]) ? str_pad($parts[1], 3, '0') : '000';

                // 将小数部分补全为3位（右侧补零）
                $decimal = str_pad($decimal, 3, '0');

                // 将小数部分和count转为整数相加，再补全为3位
                $newDecimal = (int)$decimal + (int)$count;
                $newDecimal = str_pad($newDecimal, 3, '0', STR_PAD_LEFT);

                // 处理可能的进位（如果小数部分相加超过999）
                if ($newDecimal > 999) {
                    $primary = $primary + 1;
                    $newDecimal = $newDecimal - 1000;
                    $newDecimal = str_pad($newDecimal, 3, '0', STR_PAD_LEFT);
                }

                $amount = $primary . '.' . $newDecimal;
            }

            // 记录点击事件
            $client_ip = $request->header('X-Real-IP') ?? $request->ip();
            $userAgent = $request->header('User-Agent');
            $isMobileDevice = preg_match('/(android|iphone|ipod|blackberry|windows phone)/i', $userAgent);
            $clickLog = ClickLog::create([
                'user_id' => $user_id,
                'event_type' => 'order',
                'ip' => $client_ip,
                'event_data' => json_encode([
                    'goods_id' => $goods_id,
                    'pay_way' => $pay_way,
                ]),
                'pay_way' => $pay_way,
                'is_mobile' => (bool)$isMobileDevice,
                'user_agent' => $userAgent,
                'create_day' => date('Y-m-d'),
                'order_nu' => $order_nu,
                'amount' => $amount
            ]);
            event(new ClickLogEvent($clickLog));

            // TODO 测试账号
            if (in_array($user_id, [102066])) {
                $amount = 0.01;
            }

            $order_data = [
                'user_id' => $user_id,
                'order_nu' => $order_nu,
                'goods_id' => $goods_id,
                'goods_info' => $desc,
                'proxy_type' => 2,
                'amount' => $amount,
                'quantity' => $quantity,
                'pay_way' => $pay_way,
                'extend' => json_encode([
                    'ip' => $renew_ip,
                    'days' => $renew_days
                ]),
                'is_renew' => 1,
                'create_day' => date('Y-m-d')
            ];
            $return_url = env('APP_URL') . '/manage/center/rechargeDetails?name=2';
            $result = (new PaymentService())->createPayment(Auth::user(), $pay_way, $order_nu, $amount, $desc, $return_url);
            if (empty($result)) {
                $errmsg = App::getLocale() == 'en' ? 'Order failure' : '下单失败';
                throw new \Exception($errmsg);
            }

            $order_data['amount'] = $result['amount'];
            $order_data['transaction_id'] = $result['transaction_id'];
            $order_data['transaction_platform'] = $result['transaction_platform'];

            $data = OrderInfo::create($order_data);
            if (empty($data)) {
                $errmsg = App::getLocale() == 'en' ? 'Order failure' : '下单失败';
                throw new \Exception($errmsg);
            }

            $data->locale = App::getLocale();
            $data->redirect_url = $result['redirect_url'] ?? '';
            $data->client_secret = $result['client_secret'] ?? '';
            if (empty($data->redirect_url)) {
                $config = Config::first();
                if ($pay_way == 'usdt') {
                    $data->qrcode = $config->usdt_qrcode;
                    $data->usdt_address = $config->usdt_address;
                    $data->pay_tip = __('buy.pay.usdt_tip');
                    $data->payment_note = __('buy.pay.payment_note');
                }
            }

            return response()->json([
                'errcode' => 0,
                'errmsg' => __('common.success'),
                'data' => $data
            ]);
        } catch (\Exception $e) {
            Log::error("创建订单失败：" . $e->getMessage() . ' ' . $e->getLine() . ' ' . $e->getFile());
            return response()->json([
                'errcode' => -1,
                'errmsg' => $e->getMessage(),
            ]);
        }
    }

    /**
     * 检查订单
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderCheck(Request $request)
    {
        try {
            $user_id = Auth::id();
            $order_nu = $request->input('order_nu');
            $orderInfo = OrderInfo::where('order_nu', $order_nu)->where('user_id', $user_id)->first();
            if (empty($orderInfo)) {
                return response()->json([
                    'errcode' => -1,
                    'errmsg' => __('common.invalid_operation')
                ]);
            }

            if ($orderInfo['pay_way'] == 'usdt') {
                $result = (new OrderService())->paySuccess($orderInfo->order_nu);
                if ($result['code'] != 0) {
                    return response()->json([
                        'errcode' => -1,
                        'errmsg' => __('common.check_no_pay')
                    ]);
                }
                // 订单完成事件
                event(new OrderCompletedEvent($orderInfo));
            } else {
                if ($orderInfo->status != 1) {
                    return response()->json([
                        'errcode' => -1,
                        'errmsg' => __('common.check_no_pay')
                    ]);
                }
            }

            return response()->json([
                'errcode' => 0,
                'errmsg' => __('common.purchase_success')
            ]);
        } catch (\Exception $e) {
            Log::error("创建订单失败：" . $e->getMessage() . ' ' . $e->getLine() . ' ' . $e->getFile());
            return response()->json([
                'errcode' => -1,
                'errmsg' => __('common.check_no_pay')
            ]);
        }
    }
}
